//
//  UserAccountViewModel.swift
//  SinaWeibo
//
//  Created by apple on 15/11/9.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import AFNetworking


//ViewModel 将一些业务逻辑封装到 这个类里  让这个隔离的更加好
class UserAccountViewModel: NSObject {
    
    //增加userAccount 属性
    var account: UserAccount?
    
    
    //用户是否登录的属性
    var userLogin: Bool {
        return account?.access_token != nil
    }
    
    var token: String? {
        return account?.access_token
    }
    
    var userName: String? {
        return account?.name
    }
    
    //用户头像 url
    var headURL: NSURL? {
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    
    
    //在init方法中获取 用户账户
    override init() {
        account = UserAccount.loadAccount()
    }
    
    ////加载用户token
    func loadAccessToken(code: String, finished: (error: NSError?) -> ()) {
        let urlString = "oauth2/access_token"
        let parameters = ["client_id": client_id,"client_secret":client_secret,"grant_type" : "authorization_code","code":code,"redirect_uri":redirect_uri]
        
        NetworkTools.sharedTools.requestJsonDict(.POST, urlString: urlString, parmaters: parameters) { (result, error) -> () in
            if error != nil {
                print("-----------------------")
                print(error)
                finished(error: error)
                return
            }
            
            //执行成功
            print(result)
            //开始字典转模型
            let account = UserAccount(dict:result!)
            self.loadUserInfo(account, finished: finished)
        }
    }
    
    
    //加载用户信息
    private func loadUserInfo(account: UserAccount,finished: (error: NSError?) -> ()) {
        let urlString = "2/users/show.json"
        let parmaters = ["access_token": account.access_token!, "uid": account.uid!]
        
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parmaters) { (result, error) -> () in
            if error != nil {
                finished(error: error)
                return
            }
            
            //请求用户信息
            account.avatar_large = result!["avatar_large"] as? String
            account.name = result!["name"] as? String
            
            account.saveAccount()
            
            ///执行闭包
            finished(error: nil)
        }
    }
}
